import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:kkhousekeep/net/login_connect.dart';
import 'package:kkhousekeep/net/respnse_code.dart';
import 'package:kkhousekeep/page/login/login.dart';
import 'package:kkhousekeep/tools/toast_util.dart';

import '../../config/constant.dart';

class ResetPwdPageController extends GetxController {
  ///第一个密码文本控制器
  late TextEditingController oncePwdController;

  ///第二个文本控制器
  late TextEditingController twicePwdController;

  ///是否隐藏第一个密码
  var isHideOncePwd = true.obs;

  ///是否隐藏第二个密码
  var isHideTwicePwd = true.obs;

  ///是否置灰按钮
  var isButtonAsh = true.obs;
  late LoginConnect loginConnect;
  final String phone;

  ResetPwdPageController(this.phone);

  @override
  void onInit() {
    oncePwdController = TextEditingController();
    twicePwdController = TextEditingController();

    loginConnect = Get.find<LoginConnect>();
    super.onInit();
  }

  @override
  void onClose() {
    oncePwdController.dispose();
    twicePwdController.dispose();
    super.onClose();
  }

  ///修改第一个密码显示状态
  void changeOncePwdState() {
    isHideOncePwd.value = !isHideOncePwd.value;
  }

  ///修改第二个密码显示状态
  void changeTwicePwdState() {
    isHideTwicePwd.value = !isHideTwicePwd.value;
  }

  ///观察文本
  void observerText() {
    if (oncePwdController.text.isNotEmpty &&
        twicePwdController.text.isNotEmpty) {
      isButtonAsh.value = false;
      return;
    }
    isButtonAsh.value = true;
  }

  ///重置密码
  Future<void> resetPwd() async {
    if (oncePwdController.text != twicePwdController.text) {
      ToastUtils.showToast(tip: "两次密码不一致");
      return;
    }
    if (oncePwdController.text.length < 8) {
      ToastUtils.showToast(tip: "请输入8-16位密码");
      return;
    }
    String pwd = md5
        .convert(utf8.encode("${twicePwdController.text}${Constant.pwdKey}"))
        .toString()
        .substring(0, 32);
    var response = await loginConnect.resetPwdThirdStep(phone, pwd);
    if (response == null) {
      return;
    }
    if (response.code == ResponseCode.success) {
      ToastUtils.showToast(tip: "修改密码成功");
      Get.to(() => const LoginPage());
      return;
    }
  }
}
